package org.yty.travelagencymongodb.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.DTO.HistoryGroupMessageQueryDTO;
import org.yty.travelagencymongodb.model.Entity.GroupMessage;
import org.yty.travelagencymongodb.repository.GroupMessageRepository;
import org.yty.travelagencymongodb.service.GroupMessageService;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class GroupMessageServiceImpl implements GroupMessageService {
    private final GroupMessageRepository groupMessageRepository;


    @Override
    public void save(GroupMessage groupMessage) {
        groupMessage.setCreateTime(LocalDateTime.now());
        this.groupMessageRepository.save(groupMessage);
    }

    @Override
    public List<GroupMessage> getHistoryMessages(HistoryGroupMessageQueryDTO historyGroupMessageQueryDTO) {
        Pageable pageable = PageRequest.of(historyGroupMessageQueryDTO.getPageNo().intValue(), 10, Sort.by(Sort.Direction.DESC, "createTime"));
        return this.groupMessageRepository.findByChatGroupId(historyGroupMessageQueryDTO.getChatGroupId(), pageable).get().toList();
    }

    @Override
    public List<GroupMessage> getMessages(Long chatGroupId) {
        return this.getHistoryMessages(new HistoryGroupMessageQueryDTO(chatGroupId, 0L));
    }
}
